﻿using RpcCacheClient.Interface;
using RpcHelper;
using RpcModel;
using RpcModularModel.Resource;
using RpcSync.DAL;
using RpcSync.Model;
using RpcSync.Model.DB;

namespace RpcSync.Collect.Collect
{
    internal class ResourceModularCollect : IResourceModularCollect
    {
        private IResourceModularDAL _ModularDAL;
        private ICacheController _Cache;
        public ResourceModularCollect(IResourceModularDAL modularDAL, ICacheController cache)
        {
            this._Cache = cache;
            this._ModularDAL = modularDAL;
        }

        public Guid GetModular(string name, ResourceType type, MsgSource source)
        {
            string key = string.Join("_", name, (int)type, source.SystemType, source.RpcMerId).GetMd5();
            Guid id = _FindModularId(key);
            if (id == Guid.Empty)
            {
                return this._AddModular(name, type, source, key);
            }
            return id;
        }
        private Guid _FindModularId(string key)
        {
            string cache = string.Concat("RM_", key);
            if (this._Cache.TryGet(cache, out Guid id))
            {
                return id;
            }
            id = this._ModularDAL.FindModular(key);
            if (id != Guid.Empty)
            {
                this._Cache.Add(cache, id, new TimeSpan(10, 0, 0, 0));
            }
            return id;
        }
        private Guid _AddModular(string name, ResourceType type, MsgSource source, string key)
        {
            Guid id = this._ModularDAL.AddModular(new ResourceModularModel
            {
                ModularKey = key,
                ModularName = name,
                ResourceType = type,
                SystemType = source.SystemType,
                RpcMerId = source.RpcMerId,
                AddTime = DateTime.Now,
                Id = Tools.NewGuid(),
                Remark = string.Empty
            });
            string cache = string.Concat("RM_", key);
            this._Cache.Add(cache, id, new TimeSpan(10, 0, 0, 0));
            return id;
        }
    }
}
